<!--
 * @Description: 
 * @Author: Lachlan
 * @Date: 2024-09-11 09:26:24
 * @LastEditors: 'YSJ' '951866543@qq.com'
 * @LastEditTime: 2024-09-13 17:48:44
 * @FilePath: \smart-subway\src\views\footer\SSGJPage.vue
 * 
 * Copyright (c) 2024 by Lachlan, All Rights Reserved. 
-->
<template>
  <div class="center-wrapper">
    <!-- 地铁线路 -->
    <div id="subLine-controller">
      <div class="title-bg">
        <i class="iconfont metro-lineRoute"></i> 地铁线路
      </div>
      <div class="item-wrapper">
        <div
          class="item"
          v-for="(item, index) in subLineData"
          :key="index"
          @click.stop="handleItemClick(item)"
        >
          <div
            class="box"
            :style="{
              borderColor: item.color,
              backgroundColor: item.choosed ? item.color : 'rgba(0,0,0,0)',
            }"
          ></div>
          <span :style="{ color: '#34c5cf' }">{{ item.name.slice(-3) }}</span>
        </div>
      </div>
    </div>
    <!-- 站点列表 -->
    <div id="station-controller">
      <div class="title-bg"><i class="iconfont metro-ditie"></i> 地铁站点</div>
      <div class="item-wrapper">
        <div class="item" :key="index" v-for="(item, index) in stationData">
          <div
            class="box"
            :style="{
              backgroundColor:
                index - 1 < metroIndex ? '#fff' : 'rgba(0,0,0,0)',
            }"
          ></div>
          <span :style="{ color: '#34c5cf' }">{{ item.name }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, onUnmounted } from 'vue'
import { getLine, getStationInfo } from '../../api/line'
import { useLineData } from '@/store/index'
import { getSiteTimes, spaceDistance } from '@/api/SSGJ-api/core'
import SimpleLabel from '@/cesiumTools/Bubble/htmlMarker'
import { flyToDefaultView } from '@/cesiumTools/sceneManager'

const subLineData = ref([])
const stationData = ref([])
const currentLine = ref(null)
const metroIndex = ref(0)
let viewer = null
let trainEntity = null

onMounted(async () => {
  const lineDataStore = useLineData()
  // viewer = initViewer('cesium-viewer')
  viewer = lineDataStore.Viewer

  // 获取线路数据
  subLineData.value = await getLine()
  stationData.value = subLineData.value[0].stationsList
  //   console.log(subLineData.value)

  flyToDefaultView(viewer)
})
// 移除当前的站线
const removeCurrentRoute = () => {
  currentLine.value = null
}
/* 功能:轨迹漫游 */
const handleItemClick = async (item) => {
  // 如果点击的是同一个站线，返回
  if (currentLine.value?.name == item.name) return
  removeCurrentRoute()
  console.log(item)
  currentLine.value = item
  // 点击站线，更新数据，渲染轨道列车，视角跳转，渲染popup
  const { stationsList, id } = item
  // 控制ui
  subLineData.value.forEach((item) => {
    if (item.id == id) {
      item.choosed = true
    } else {
      item.choosed = false
    }
  })
  stationData.value = stationsList
  // 从模拟服务端获取列车信息
  const trainInfo = await getTrainDataByLineId(id)
  // 渲染轨道列车
  renderTrain(trainInfo)
  // 渲染气泡框
  renderBubble(trainInfo)
}

// 构建气泡框
let trainPopup
const renderBubble = (trainInfo) => {
  trainPopup && trainPopup.removeMarker()
  // 构建数据
  const options = {
    type: 'carPopup',
    attr: {
      lineName: trainInfo.lineName,
      currentPassengers: trainInfo.currentPassengers,
    },
    offset: [150, 250],
  }
  trainPopup = new SimpleLabel(viewer, options)
  viewer.scene.postRender.addEventListener(() => {
    const position = trainEntity.position.getValue(viewer.clock.currentTime)
    trainPopup.changePosition(position)
  })
  trainPopup.addLabel()
}

// 假设从服务端获取到列车的实时信息
const getTrainDataByLineId = (id) => {
  return new Promise((resolve, reject) => {
    // 构造一个随机的站点index
    let startIndex = 0
    const startStationInfo = stationData.value[startIndex]
    const endStationInfo = stationData.value[startIndex + 1]
    // 由于站点坐标和路径坐标可能不会完全匹配，这里只是模拟数据，给列车虚构一个坐标点
    const trainData = {
      startIndex,
      currentPassengers: Math.ceil(Math.random() * 1000),
      startStation: startStationInfo,
      destination: endStationInfo,
      lineName: currentLine.value.name,
      currentSpeed: Math.ceil(Math.random() * 100),
      currentPosition: currentLine.value.paths[2],
    }
    resolve(trainData)
  })
}
// 渲染轨道列车
const renderTrain = (trainInfo) => {
  //移除之前的列车
  trainEntity && viewer.entities.remove(trainEntity)
  // 获取出发站点，得到metroIndex
  const { startIndex, currentPosition, currentSpeed } = trainInfo
  metroIndex.value = startIndex
  const pathIndex = currentLine.value.paths.findIndex(
    (path) => path === currentPosition
  )
  const { property, startTime, endTime } = handlePosition(
    currentSpeed,
    pathIndex
  )
  trainEntity = viewer.entities.add({
    availability: new Cesium.TimeIntervalCollection([
      new Cesium.TimeInterval({
        start: startTime,
        stop: endTime,
      }),
    ]),
    position: property,
    orientation: new Cesium.VelocityOrientationProperty(property),
    model: {
      scale: 0.17,
      uri: '/src/assets/model/metro.gltf',
      minimumPixelSize: 40,
    },
  })

  viewer.trackedEntity = trainEntity
  viewer.clock.startTime = startTime.clone()
  viewer.clock.stopTime = endTime.clone()
  viewer.clock.currentTime = startTime.clone()
  // 监听时钟，如果列车到达站点，更新列车人数信息，并给一个暂停时间
  viewer.clock.onTick.addEventListener(tickEventHandler)
}

/* 😊使用availability和sampledProperty实现列车轨迹漫游 */
// 处理漫游效果，使用TimeIntervalCollection
const handlePosition = (speed, pathIndex) => {
  const property = new Cesium.SampledProperty(Cesium.Cartesian3)
  // 这里的时间可以自己定义
  let startTime = Cesium.JulianDate.fromDate(new Date(2015, 1, 1, 8))
  //通过速度计算最终时间
  const restPath = currentLine.value.paths.slice(
    pathIndex,
    currentLine.value.paths.length - 1
  )
  //转为Caterian3数组
  const getPositions = (path) => {
    return path.map((item) => {
      return Cesium.Cartesian3.fromDegrees(item.lng, item.lat)
    })
  }
  const positions = getPositions(restPath)
  //根据速度计算总时间和每段时间
  const { siteTimes, timeSum } = getSiteTimes(positions, speed)
  const endTime = Cesium.JulianDate.addSeconds(
    startTime,
    timeSum,
    new Cesium.JulianDate()
  )
  positions.forEach((position, index) => {
    const time = Cesium.JulianDate.addSeconds(
      startTime,
      siteTimes[index],
      new Cesium.JulianDate()
    )
    property.addSample(time, position)
  })
  return {
    property,
    startTime,
    endTime,
  }
}

/* 😊监听列车与站点距离，实现到站效果 */
// 当距离小于20米的时候，就可以给列车一个暂停
let popupController
let apporachDistance = 20
const tickEventHandler = async () => {
  const startPosition = trainEntity.position.getValue(viewer.clock.currentTime)
  //通过当前的metroIndex和速度计算下一个站点的坐标
  const { position } = stationData.value[metroIndex.value + 1]
  const endPosition = new Cesium.Cartesian3.fromDegrees(
    position.lng,
    position.lat
  )
  let distance = Cesium.Cartesian3.distance(startPosition, endPosition)
  if (distance <= apporachDistance) {
    // 站点id变大，下一次计算的distance也会变大
    metroIndex.value++
    // 将列车暂停
    viewer.clock.shouldAnimate = false
    // 显示popup
    const trainInfo = await getTrainDataByLineId()
    renderBubble(trainInfo)
    // 2s后恢复

    setTimeout(() => {
      viewer.clock.shouldAnimate = true
    }, 2000)
  }
  // 还需要通过startPosition计算气泡框坐标
  popupController && popupController.changePosition(startPosition)
}

// 组件销毁时的清理操作
onBeforeUnmount(() => {
  // controAll(subLineData.value, true)
  trainEntity && viewer.entities.remove(trainEntity)
  trainPopup && trainPopup.removeMarker()
  viewer.clock.onTick.removeEventListener(tickEventHandler)
})
</script>

<style scoped>
.wrapper {
  width: 100%;
  height: 100%;
}

/* 地铁线路列表 */
#subLine-controller {
  position: absolute;
  bottom: 85px;
  left: 32.5%;
  transform: translateX(-50%);
  width: 180px;
  height: 200px;
  background-color: rgba(0, 0, 0, 0.3);
  border: 1px solid #ab7818;
  display: flex;
  flex-direction: column;
}

.box {
  width: 10px;
  height: 10px;
  border-width: 1px;
  border-style: solid;
  background: transparent;
  user-select: all;
  cursor: pointer;
  transition: all 0.3s linear;
}

.item {
  width: 64.992px;
  height: 20.006px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 0.156vw;
  background-color: rgba(255, 255, 255, 0.2);
  border: 1px solid #885f12;
  color: #fff;
  font-size: 0.521vw;
  pointer-events: all;
}

.item:hover {
  border: 1px solid #d8961a;
}

.item > span {
  line-height: 0.469vw;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 2.083vw;
}

.item > input {
  outline: none;
  border: none;
  transition: all 0.3s ease;
}

.item-wrapper {
  display: flex;
  justify-content: space-around;
  align-content: space-around;
  flex-wrap: wrap;
  flex: 1;
  padding: 4px;
  overflow: hidden;
}

/* 站点列表 */
#station-controller {
  width: 600px;
  height: 200px;
  border: 1px solid #ab7818;
  background-color: rgba(0, 0, 0, 0.3);
  position: absolute;
  left: 38%;
  bottom: 85px;
  color: #fff;
  display: flex;
  flex-direction: column;
}

#station-controller .item-wrapper {
  justify-content: flex-start;
}

#station-controller .item {
  margin: 0 7px;
}

.title-bg {
  width: 100%;
  height: 30px;
  background: url('/src/assets/uiResources/title-bg.png');
  background-size: contain;
  color: #fff;
  background-repeat: no-repeat;
  line-height: 30px;
  margin-left: 10px;
  background: rgb(255, 255, 255);
  background-image: linear-gradient(
    180deg,
    rgba(255, 255, 255, 1) 9%,
    rgba(211, 156, 50, 1) 57%
  );
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
}

/* 站控措施图例 */
.right-wrapper {
  width: 11.417vw;
  height: 100%;
  position: absolute;
  right: 0px;
  top: 2.083vw;
}

.right-wrapper .query-item-title {
  cursor: default;
  pointer-events: none;
}

.right-wrapper .query-item-title::after {
  width: 20px;
  left: -20px;
}

.legend .query-item i {
  pointer-events: none;
  cursor: default;
}

.title {
  color: #fff;
}
</style>
